#include "pipe_recv_buff.h"

const size_t PipeRecvBuff::MAX_LENGTH_BUFF_SIZE = 64;
const size_t PipeRecvBuff::MAX_DATA_BUFF_SIZE   = 10240;

PipeRecvBuff::PipeRecvBuff(): Buff() {
	length_buff = new char[MAX_LENGTH_BUFF_SIZE+10];
	data_buff   = new char[MAX_DATA_BUFF_SIZE+10];
	
	//memset(length_buff, 0, sizeof(char)*(MAX_LENGTH_BUFF_SIZE+10));
	//memset(data_buff, 0, sizeof(char)*(MAX_DATA_BUFF_SIZE+10));

	data_length = 0;
	block_count = 0;
	status = 0;
	index  = 0;
	remain = 0;
}

PipeRecvBuff::~PipeRecvBuff() {
	delete[] length_buff;
	delete[] data_buff;
}

ssize_t PipeRecvBuff::recv_length(int fd) {
	ssize_t tot = 0;
	while (true) {
		ssize_t n = read(fd, length_buff + index, 1);
		if (n == -1 || n == 0) return n;
		if (length_buff[index] == '|') {
			length_buff[index] = '\0';
			break;
		}
		index += n;
		tot += n;
	}
	status = 1;
	return tot;
}

ssize_t PipeRecvBuff::recv_data(int fd) {
	ssize_t tot = 0;
	while (remain > 0) {
		ssize_t n = read(fd, data_buff, remain);
		if (n == -1 || n == 0) return n;
		tot += n;
		index += n;
		remain -= n;
	}
	status = 2;
	return tot;
}

void PipeRecvBuff::get_length() {
	sscanf(length_buff, "%d:%d", &data_length, &block_count);
	index = 0;
	remain = data_length;
}

bool PipeRecvBuff::finish_length() {
	return status >= 1;
}

bool PipeRecvBuff::finish_data() {
	return status >= 2;
}

void PipeRecvBuff::reset() {
	memset(length_buff, 0, sizeof(char)*(MAX_LENGTH_BUFF_SIZE+10));
	memset(data_buff, 0, sizeof(char)*(MAX_DATA_BUFF_SIZE+10));

	data_length = 0;
	block_count = 0;
	status = 0;
	index  = 0;
	remain = 0;

}
